﻿
namespace WMS.Common
{
    /// <summary>
    /// GUID帮助类 - 生成全球唯一标识符
    /// </summary>
    public static class GuidHelper
    {
        /// <summary>
        /// 生成标准的GUID格式
        /// 格式: 00000000-0000-0000-0000-000000000000
        /// </summary>
        public static string Generate()
        {
            return Guid.NewGuid().ToString();
        }

        /// <summary>
        /// 生成无连字符的GUID
        /// 格式: 00000000000000000000000000000000
        /// </summary>
        public static string GenerateWithoutDash()
        {
            return Guid.NewGuid().ToString("N");
        }

        /// <summary>
        /// 生成大写的GUID（无连字符）
        /// 格式: 00000000000000000000000000000000
        /// </summary>
        public static string GenerateUpperCase()
        {
            return Guid.NewGuid().ToString("N").ToUpper();
        }

        /// <summary>
        /// 生成带前缀的GUID
        /// 格式: PREFIX_00000000000000000000000000000000
        /// </summary>
        public static string GenerateWithPrefix(string prefix)
        {
            if (string.IsNullOrWhiteSpace(prefix))
                return GenerateWithoutDash();

            return $"{prefix}_{GenerateWithoutDash()}";
        }

        /// <summary>
        /// 生成带前缀和时间戳的GUID
        /// 格式: PREFIX_20231108_00000000000000000000000000000000
        /// </summary>
        public static string GenerateWithPrefixAndTimestamp(string prefix)
        {
            var timestamp = DateTime.Now.ToString("yyyyMMdd");
            var guid = GenerateWithoutDash();

            if (string.IsNullOrWhiteSpace(prefix))
                return $"{timestamp}_{guid}";

            return $"{prefix}_{timestamp}_{guid}";
        }

        /// <summary>
        /// 生成短GUID（Base64编码，去除特殊字符）
        /// 长度: 22位
        /// </summary>
        public static string GenerateShort()
        {
            var guid = Guid.NewGuid().ToByteArray();
            return Convert.ToBase64String(guid)
                .Replace("/", "_")
                .Replace("+", "-")
                .Substring(0, 22);
        }

        /// <summary>
        /// 生成指定长度的GUID（截取前N位）
        /// </summary>
        public static string GenerateLength(int length)
        {
            if (length <= 0 || length > 32)
                throw new ArgumentException("长度必须在1-32之间");

            return GenerateWithoutDash().Substring(0, length);
        }

        /// <summary>
        /// 验证字符串是否为有效的GUID格式
        /// </summary>
        public static bool IsValidGuid(string guidString)
        {
            if (string.IsNullOrWhiteSpace(guidString))
                return false;

            return Guid.TryParse(guidString, out _);
        }

        /// <summary>
        /// 从字符串创建GUID，如果无效则生成新的
        /// </summary>
        public static string CreateOrGenerate(string guidString)
        {
            if (IsValidGuid(guidString))
                return guidString;

            return Generate();
        }
    }
}
